package cn.exrick.xboot.cummunity.controller;

import cn.exrick.xboot.core.common.redis.RedisTemplateHelper;
import cn.exrick.xboot.core.common.utils.PageUtil;
import cn.exrick.xboot.core.common.utils.ResultUtil;
import cn.exrick.xboot.core.common.utils.SecurityUtil;
import cn.exrick.xboot.core.common.vo.PageVo;
import cn.exrick.xboot.core.common.vo.Result;
import cn.exrick.xboot.core.entity.Member;
import cn.exrick.xboot.core.service.MemberService;
import cn.exrick.xboot.cummunity.entity.CumOrder;
import cn.exrick.xboot.cummunity.service.ICumOrderService;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
* <p>
    * 社区跑腿-订单列表  前端控制器
    * </p>
*
* @author xujiaxin
* @since 2024-08-22
*/
@RestController
@RequestMapping("/xboot/cumorder")
public class CumOrderController {

    @Autowired
    private ICumOrderService cumOrderService;

    @Autowired
    private SecurityUtil securityUtil;

    @Autowired
    private MemberService memberService;

    @Autowired
    private RedisTemplateHelper redisTemplate;

    private final String ORDER_STATUS = "orderStatus_";

    /**
     * 创建订单
     * @param cumOrder
     * @return
     */
    @PostMapping("createOrder")
    public Result crateOrder(@RequestBody CumOrder cumOrder){

        Member m = securityUtil.getCurrMember();
        cumOrder.setCreateDate(new Date());
        cumOrder.setCreateUser(m.getId());
        cumOrder.setCreateUserName(m.getNickname());
        cumOrder.setCreateUserOpenid(m.getOpenId());
        cumOrder.setOrderStatus("发布");
        cumOrderService.save(cumOrder);
        return ResultUtil.data(cumOrder);
    }

    /**
     * 获取订单列表
     * @param pageVo
     * @param order
     * @return
     */
    @GetMapping("getOrderList")
    public Result<IPage<CumOrder>> getOrderList(PageVo pageVo, CumOrder order){
        Page page = PageUtil.initMpPage(pageVo);
        QueryWrapper<CumOrder> wrapper = new QueryWrapper<CumOrder>();
        wrapper.eq("order_status", "发布");
        this.setWrapper(order, wrapper);
        wrapper.orderByDesc("create_date");
        IPage<CumOrder> ipage = cumOrderService.page(page, wrapper);
        return new ResultUtil<IPage<CumOrder>>().setData(ipage);
    }

    public void setWrapper(CumOrder order, QueryWrapper<CumOrder> wrapper) {
        if(StrUtil.isNotBlank(order.getReqType())){
            wrapper.eq("req_type", order.getReqType());
        }
    }

    /**
     * 接受订单
     * @param id
     * @return
     */
    @PostMapping("pickOrder")
    public Result pickOrder(Integer id){
        Member m = securityUtil.getCurrMember();
        // 判断有无接单权限
        if(!m.getPermissions().contains("WORKER")) {
            return new ResultUtil<>().setErrorMsg("无权限接单");
        }
        // 判断订单是否被占用
        String orderStatus = redisTemplate.get(ORDER_STATUS + id);
        if(StrUtil.isNotBlank(orderStatus)){
            return new ResultUtil<>().setErrorMsg("订单已被占用");
        }
        // redis设置接单状态，60秒过期防止占用
        redisTemplate.set(ORDER_STATUS + id, "接单中", 60, TimeUnit.SECONDS);
        CumOrder cumOrder = cumOrderService.getById(id);
        if(!cumOrder.getOrderStatus().equals("发布")){
            redisTemplate.delete(ORDER_STATUS + id);
            return new ResultUtil<>().setErrorMsg("订单已被占用");
        }


        cumOrder.setOrderStatus("已接单");
        cumOrder.setPickUser(m.getId());
        cumOrder.setPickDate(new Date());
        cumOrder.setPickUserAvatar(m.getAvatar());
        cumOrder.setPickUserName(m.getNickname());
        cumOrder.setPickUserPhone(m.getMobile());
        cumOrder.setPickUserOpenid(m.getOpenId());
        cumOrderService.updateById(cumOrder);
        redisTemplate.delete(ORDER_STATUS + id);
        return  ResultUtil.data(cumOrder);
    }

    /**
     * 获取我的订单列表
     * @param pageVo
     * @param order
     * @return
     */
    @GetMapping("myOrderList")
    public Result<IPage<CumOrder>> myOrderList(PageVo pageVo, CumOrder order){
        Page page = PageUtil.initMpPage(pageVo);
        QueryWrapper<CumOrder> wrapper = new QueryWrapper<CumOrder>();
        if(StrUtil.isNotBlank(order.getOrderStatus()) && !order.getOrderStatus().equals("全部")){
            wrapper.eq("order_status", order.getOrderStatus());
        }
        wrapper.nested(w -> w.eq("create_user", securityUtil.getCurrMember().getId()).or().eq("pick_user", securityUtil.getCurrMember().getId()));
        wrapper.orderByDesc("create_date");
        IPage<CumOrder> ipage = cumOrderService.page(page, wrapper);
        return new ResultUtil<IPage<CumOrder>>().setData(ipage);
    }
}
